package com.lqclass.demo.interceptor;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lqclass.demo.domain.User;
import com.lqclass.demo.service.impl.UserServiceImpl;
import com.lqclass.demo.utils.JsonData;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

class LoginInterceptor implements HandlerInterceptor {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println("LoginInterceptor preHandle =====");

        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)){
            token = request.getParameter("token");
        }

        if(StringUtils.isEmpty(token)){

            renderJson(response, JsonData.buildError("未登录", -3));
            return false;

        }

        // 判断token是否合法
        User user = UserServiceImpl.sessionMap.get(token);
        if(user != null){

            return true;
        }

        renderJson(response, JsonData.buildError("登录失败，token无效", -2));
        return false;
        //return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    /**
     * 登录拦截，验证失败时，返回有效信息
     * @param response
     * @param jsonData
     * @throws JsonProcessingException
     */
    private void renderJson(HttpServletResponse response, JsonData jsonData) throws JsonProcessingException {

        String jsonStr = objectMapper.writeValueAsString(jsonData);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");

        try(PrintWriter writer = response.getWriter()){
            writer.print(jsonStr);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        System.out.println("LoginInterceptor postHandle =====");

        HandlerInterceptor.super.postHandle(request,response,handler,modelAndView);

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        System.out.println("LoginInterceptor afterCompletion =====");

        HandlerInterceptor.super.afterCompletion(request,response,handler,ex);
    }
}